﻿namespace AuroraLightsFX
{
    using System;
    using System.IO;
    
    internal static class LedControlManager
    {
        private static bool _conected = false;
        private static LEDcontrol _ledControl = new LEDcontrol();
        private static Delay _wait = new Delay();

        public static bool CompareFirmware(string romFile, LEDcontrol.SetPercentValueDelegate percentDelegate)
        {
            return CompareFirmware(romFile, percentDelegate, false);
        }

        public static bool CompareFirmware(string romFile, LEDcontrol.SetPercentValueDelegate percentDelegate, bool usingTesting)
        {
            if (!tryToConnect())
            {
                return false;
            }
            byte token = usingTesting ? ((byte) 0xff) : ((byte) 0);
            bool flag = File.Exists(romFile);
            if (flag)
            {
                FileStream stream = File.Open(romFile, FileMode.Open);
                int length = (int) stream.Length;
                byte[] buffer = new byte[length];
                stream.Read(buffer, 0, length);
                stream.Close();
                byte[] inbuf = new byte[length];
                flag = _ledControl.EEpromRead(token, 0, (uint) length, inbuf, percentDelegate);
                for (int i = 0; (i < length) && flag; i++)
                {
                    flag = buffer[i] == inbuf[i];
                }
            }
            return flag;
        }

        private static void delay(int milliseconds)
        {
            _wait.Sleep(milliseconds);
        }

        private static bool openAndResetDevice()
        {
            bool flag = false;
            flag = _ledControl.OpenDeviceIfNeeded(true);
            if (flag)
            {
                flag = SendResetCommand(false);
            }
            return flag;
        }

        public static bool ReadFirmwareVersion(ref string version)
        {
            version = "";
            bool firmwareVersion = tryToConnect();
            if (firmwareVersion)
            {
                firmwareVersion = _ledControl.GetFirmwareVersion(out version);
                if (!firmwareVersion)
                {
                    return firmwareVersion;
                }
                try
                {
                    decimal num = Convert.ToDecimal(version.Substring(1)) / 10000M;
                    string str = num.ToString("0.0000");
                    string str2 = ((int) num).ToString();
                    string str3 = str.Substring(str.IndexOf('.') + 1, 2);
                    string str4 = str.Substring(str.Length - 2);
                    version = string.Format("{0}.{1}.{2}", str2, str3, str4);
                }
                catch
                {
                    version = "";
                    firmwareVersion = false;
                }
            }
            return firmwareVersion;
        }

        public static bool ReadSerialNumber(ref string serialNumber)
        {
            serialNumber = "";
            bool flag = tryToConnect();
            if (flag)
            {
                flag = _ledControl.GetSerialNumber(out serialNumber);
                serialNumber = string.Format("{0:X}", serialNumber);
            }
            return flag;
        }

        public static bool RebootROM()
        {
            if (!tryToConnect())
            {
                return false;
            }
            return _ledControl.RebootRom();
        }

        public static bool Reconnect()
        {
            bool flag = _ledControl.OpenDeviceIfNeeded(true);
            if (flag)
            {
                flag = SendResetCommand(false);
            }
            _conected = flag;
            return _conected;
        }

        public static bool Reconnect(int attemps)
        {
            bool flag = false;
            for (int i = 0; (i < attemps) && !flag; i++)
            {
                delay(0x1388);
                flag = _ledControl.OpenDeviceIfNeeded(true);
            }
            if (flag)
            {
                flag = SendResetCommand(false);
            }
            _conected = flag;
            return flag;
        }

        public static bool SendPacket(GroupPacket packet)
        {
            return SendPacket(packet, true);
        }

        public static bool SendPacket(GroupPacket packet, bool FirstDoReset)
        {
            if (!tryToConnect())
            {
                return false;
            }
            if (((packet == null) || (packet.GroupActionsInfoCommands == null)) || (packet.GroupActionsInfoCommands.Count <= 0))
            {
                return false;
            }
            bool flag = false;
            if (FirstDoReset)
            {
                flag = SendResetCommand(false);
                if (!flag)
                {
                    return false;
                }
            }
            foreach (byte[] buffer in packet.GroupActionsInfoCommands)
            {
                //FORTEST
                //_ledControl.EEpromWrite(0, 0, buffer.Length - 1, buffer);
                flag = _ledControl.SendCommand(buffer);
                if (!flag)
                {
                    return flag;
                }
            }
            return flag;
        }

        public static void SendPacketToROM(GroupPacket packet)
        {

            if (!tryToConnect())
            {
                return;
            }
            if (((packet == null) || (packet.GroupActionsInfoCommands == null)) || (packet.GroupActionsInfoCommands.Count <= 0))
            {
                return;
            }

            if (!_ledControl.SendSpecialReset(LEDcontrol.ResetModifiers.Leave_Lights_On, 0))
                return;
            
            bool flag = false;

            foreach (byte[] buffer in packet.GroupActionsInfoCommands)
            {
                //FORTEST
                flag = _ledControl.EEpromWrite(1, 0, buffer.Length - 1, buffer);
                if (!flag)
                {
                    return;
                }
            }
            SendEmptyPacketToROM();

        }

        public static void SendEmptyPacketToROM()
        {
            byte[] send = new byte[8];

            _ledControl.EEpromWrite(1, 0, 8, send);
            _ledControl.EEpromWriteFinished();
        }
        public static bool SendSpecialReset(LEDcontrol.ResetModifiers resetModifier, int actionDuration)
        {
            return _ledControl.SendSpecialReset(resetModifier, actionDuration);
        }
        public static bool SendResetCommand(bool forceReset)
        {
            if (_ledControl == null)
            {
                return false;
            }
            bool flag = true;
            if (forceReset || (_ledControl.GetStatus() != LEDcontrol.DeviceStatus.Ready))
            {
                flag = _ledControl.SendReset();
                if (flag)
                {
                    flag = waitForReady();
                }
            }
            return flag;
        }

        public static bool SendStart()
        {
            if (!tryToConnect())
            {
                return false;
            }
            return _ledControl.SendStart();
        }

        private static bool tryToConnect()
        {
            if (!_conected)
            {
                _conected = openAndResetDevice();
            }
            return _conected;
        }

        private static bool waitForReady()
        {
            return waitForReady(true);
        }

        private static bool waitForReady(bool delayBeforeBegin)
        {
            int milliseconds = 0x5dc;
            if (_ledControl.ProductId == 0x511)
            {
                milliseconds = 200;
            }
            if (delayBeforeBegin)
            {
                delay(milliseconds);
            }
            LEDcontrol.DeviceStatus status = _ledControl.GetStatus();
            int num2 = 0;
            while ((status != LEDcontrol.DeviceStatus.Ready) && (num2 < 10))
            {
                delay(milliseconds);
                num2++;
                status = _ledControl.GetStatus();
            }
            return (num2 != 10);
        }

        public static bool WriteFirmware(string romFile, LEDcontrol.SetPercentValueDelegate percentDelegate)
        {
            return WriteFirmware(romFile, percentDelegate, false);
        }

        public static bool WriteFirmware(string romFile, LEDcontrol.SetPercentValueDelegate percentDelegate, bool usingTesting)
        {
            if (!tryToConnect())
            {
                return false;
            }
            byte token = usingTesting ? ((byte) 0xff) : ((byte) 0);
            bool flag = File.Exists(romFile);
            if (flag)
            {
                FileStream stream = File.Open(romFile, FileMode.Open);
                int length = (int) stream.Length;
                byte[] buffer = new byte[length];
                stream.Read(buffer, 0, length);
                stream.Close();
                flag = _ledControl.EEpromWrite(token, 0, length, buffer, percentDelegate);
                flag = _ledControl.EEpromWriteFinished();
            }
            return flag;
        }

        public static bool Conected
        {
            get
            {
                return _conected;
            }
        }

        public static int ProductID
        {
            get
            {
                return _ledControl.ProductId;
            }
        }

        public static int VendorID
        {
            get
            {
                return _ledControl.VendorId;
            }
        }
    }
}

